package com.zzr.jdk8.source.demo.collection;

import org.junit.Test;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author: xiaomi
 * @date: 2021/9/11
 * @description:
 */
public class HashSetDemo {

    @Test
    public void demo1() {
        Set<Object> set = new HashSet<>();
        set.add(new Dog("tom"));
        set.add(new Dog("tom"));
        set.add(new String("hsp"));
        set.add(new String("hsp"));
        //set = [Dog{name='tom'}, hsp, Dog{name='tom'}]
        //关于 hsp 可以去补充 jvm 知识
        System.out.println("set = " + set);
    }

    /**
     * 测试 equals 时是否覆盖
     * NOTEME 在 hash() 和 equals() 都相同时就会放弃
     */
    @Test
    public void demo2() {
        Set<Object> set = new HashSet<>();
        set.add(new Toy(1));
        //如果发现相同就放弃添加！！
        set.add(new Toy(2));
        System.out.println("set = " + set);
    }

    class Dog {
        private String name;

        public Dog(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Dog{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    class Toy {
        private int no;

        public Toy(int no) {
            this.no = no;
        }

        @Override
        public String toString() {
            return "Toy{" +
                    "no=" + no +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Toy toy = (Toy) o;
            return true;
        }

        @Override
        public int hashCode() {
            return 1;
        }
    }

}
